<template>
    <div class="map-page">
        <div class="header">
            <div class="left">北京市</div>
            <div class="select1">
                <a-input v-model:value="value1" style="width: 240px
                ;" placeholder="请输入城市" @keyup.enter="handleSearchCity">

                </a-input>
            </div>
            <div class="select1">
                <a-select v-model:value="select1" style="width: 240px
                ;" placeholder="请选择绘制图形" @change="handleDrawType">
                    <a-select-option v-for="item in options" :value="item.value">{{ item.label }} </a-select-option>

                </a-select>
            </div>
            <div class="select2">
                <a-select v-model:value="select2" style="width: 240px
                ;" placeholder="请选择图标类型">
                    <a-select-option v-for="item in icons" :value="item.value">{{ item.label }} </a-select-option>

                </a-select>
            </div>

        </div>
        <!-- 地图容器 -->
        <div ref="mapContainer" class="map-container"></div>
        <div id="popup" v-html="popupContent"></div>
    </div>
</template>

<script>
import Map from 'ol/Map'
import View from 'ol/View'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { XYZ, Vector as VectorSource } from 'ol/source'
// import { defaults as defaultControls } from 'ol/control';
import { defaults, Rotate } from 'ol/control';
import FullScreen from 'ol/control/FullScreen.js';
import ZoomSlider from 'ol/control/ZoomSlider.js';
import MousePosition from 'ol/control/MousePosition.js';
import axios from 'axios'
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style.js';
import GeoJSON from 'ol/format/GeoJSON';
import Stroke from 'ol/style/Stroke.js';
import Draw from 'ol/interaction/Draw.js';
import Overlay from 'ol/Overlay';
import service from '@/utils/request' // 导入封装的axios实例
export default {
    name: 'MapComponent',
    data() {
        return {
            map: null,
            value1: '北京',
            select1: undefined,
            select2: undefined,
            options: [
                {
                    label: '直线',
                    value: 'line'
                },
                {
                    label: '圆形',
                    value: 'circle'
                },
                {
                    label: '面',
                    value: 'polygon'
                },
                {
                    label: '自由',
                    value: 'free'
                },
                {
                    label: '清除绘图',
                    value: 'clear'
                },
            ],
            icons: [
                {
                    label: '充电站',
                    value: 'charge'
                },
                {
                    label: '公交站',
                    value: 'bus'
                },
                {
                    label: '退出标记',
                    value: 'exit'
                },
            ],
            cityLayer: null,
            adcode: null,
            drawLayer: null,
            draw: null,
            popup: null,
            popupContent: null,
        }
    },

    mounted() {
        this.$nextTick(() => {
            this.initMap()
        })
    },

    methods: {
        async initMap() {
            // 初始化底图
            const gaodeLayer = new TileLayer({
                source: new XYZ({
                    // url: 'https://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                    // crossOrigin: 'anonymous'
                    url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
                    // attributions: '© <a href="https://www.amap.com/">高德地图</a>'
                })
            })

            // 创建地图
            this.map = new Map({ // 添加这个配置
                target: this.$refs.mapContainer,
                layers: [gaodeLayer],
                view: new View({
                    center: [116.3974, 39.9093],
                    zoom: 3,
                    minZoom: 3,
                    maxZoom: 18,
                    // projection: 'EPSG:4326'
                    enableRotation: true,
                }),
                controls: defaults({
                    attribution: true,
                    zoom: true,
                    rotate: true, // 确保旋转控制启用
                }),
                canvas: {
                    willReadFrequently: true
                },
            });

            this.drawLayer = new VectorLayer({
                source: new VectorSource(),
                style: new Style({
                    fill: new Fill({
                        color: 'rgba(255,0,0,0.5)'
                    }),
                    stroke: new Stroke({
                        color: 'black',
                        width: 2
                    })
                })
            })
            this.map.addLayer(this.drawLayer)




            //请求 高德 json
            // 使用代理路径，不要包含高德域名

            // const response1 = await fetch('https://restapi.amap.com/v3/ip?key=e939b265c4f03221761bf17c5fd1845b');
            // const data1 = await response1.json(); // 需要再次 await
            // console.log('ip:', data1);


            // const response2 = await fetch(`https://restapi.amap.com/v3/geocode/geo?key=e939b265c4f03221761bf17c5fd1845b&address=${this.value1}`);
            const response2 = await service.get('/amap/v3/geocode/geo', {
                params: {
                    key: 'e939b265c4f03221761bf17c5fd1845b',
                    address: this.value1
                }
            });
            const data2 = response2; // 需要再次 await
            // const response2 = await fetch(`https://restapi.amap.com/v3/geocode/geo?key=e939b265c4f03221761bf17c5fd1845b&address=${this.value1}`);
            // const data2 = await response2.json(); // 需要再次 await

            console.log('地理编码结果:', data2);
            this.adcode = data2.geocodes[0].adcode

            this.cityLocation = data2.geocodes[0].location.split(',').map(Number);
            console.log(this.cityLocation);



            setTimeout(() => {
                this.cityLayer = new VectorLayer({
                    className: 'city-layer',

                    source: new VectorSource({
                        url: `https://geo.datav.aliyun.com/areas_v3/bound/${this.adcode}.json`,
                        format: new GeoJSON()
                    }),
                    style: new Style({
                        fill: new Fill({
                            color: 'rgba(255,0,0,0.5)'
                        }),
                        stroke: new Stroke({
                            color: 'black',
                            width: 2
                        })
                    })
                })

                this.map.addLayer(this.cityLayer)

                this.map.getView().animate({
                    center: this.cityLocation,
                    zoom: 8,
                    duration: 2000
                })

            }, 1000)

            let that = this
            this.map.getView().on('change:resolution', function () {

                let zoom = this.getZoom()

                if (zoom > 10) {
                    that.cityLayer.setVisible(false)
                    that.drawLayer.setVisible(false)
                } else {
                    that.cityLayer.setVisible(true)
                    that.drawLayer.setVisible(false)
                }
            })

            this.map.on('click', function (e) {
                const pixel = e.pixel
                const features = that.map.getFeaturesAtPixel(pixel)
                if (features.length > 0 && features[0].get('name')) {
                    const center = features[0].get('center')
                    const name = features[0].get('name')
                    that.popup = new Overlay({
                        element: document.getElementById('popup')
                    })
                    that.popup.setPosition(center)
                    that.popupContent = `
                    <p>当前城市是: ${name}</p>
                    <p>经度: ${center[0]}</p>
                    <p>维度: ${center[1]}</p>

                    `
                    that.map.addOverlay(that.popup)
                } else {
                    if (that.popup) {
                        that.popup.setPosition(undefined)
                    }
                }

            })


        },

        async handleSearchCity() {
            let allLayers = this.map.getLayers()

            let allLayers1 = allLayers.getArray().filter((layer) => { return layer.getClassName() === 'city-layer' })
            if (allLayers1.length > 0) {
                allLayers1.forEach(element => {
                    this.map.removeLayer(element)

                });

            }

            const response2 = await fetch(`https://restapi.amap.com/v3/geocode/geo?key=e939b265c4f03221761bf17c5fd1845b&address=${this.value1}`);
            const data2 = await response2.json(); // 需要再次 await
            console.log('地理编码结果:', data2);
            this.adcode = data2.geocodes[0].adcode
            this.cityLocation = data2.geocodes[0].location.split(',').map(Number);
            console.log(this.cityLocation);

            setTimeout(() => {
                this.cityLayer = new VectorLayer({
                    className: 'city-layer',
                    source: new VectorSource({
                        url: `https://geo.datav.aliyun.com/areas_v3/bound/${this.adcode}.json`,
                        format: new GeoJSON()
                    }),
                    style: new Style({
                        fill: new Fill({
                            color: 'rgba(255,0,0,0.5)'
                        }),
                        stroke: new Stroke({
                            color: 'black',
                            width: 2
                        })
                    })
                })

                this.map.addLayer(this.cityLayer)

                this.map.getView().animate({
                    center: this.cityLocation,
                    zoom: 8,
                    duration: 2000
                })

            }, 1000)


        },

        handleDrawType() {
            if (this.select1 == 'clear') {
                this.drawLayer.getSource().clear()

                this.select1 = undefined
                this.map.removeInteraction(this.draw)

            } else {
                this.map.removeInteraction(this.draw)
                if (this.select1 == 'line') {
                    this.draw = new Draw({
                        type: 'LineString',
                        source: this.drawLayer.getSource(),
                    })

                } else if (this.select1 == 'circle') {
                    this.draw = new Draw({
                        type: 'Circle',
                        source: this.drawLayer.getSource(),
                    })
                } else if (this.select1 == 'polygon') {
                    this.draw = new Draw({
                        type: 'Polygon',
                        source: this.drawLayer.getSource(),
                    })
                } else {
                    this.draw = new Draw({
                        type: 'LineString',
                        source: this.drawLayer.getSource(),
                        freehand: true
                    })
                }
                this.map.addInteraction(this.draw)
                this.drawLayer.setVisible(true)
            }

        },
        // handleDrawType() {
        //     if (this.select1 == 'clear') {
        //         this.drawLayer.getSource().clear()
        //         this.select1 = undefined
        //         this.map.removeInteraction(this.draw)
        //     } else {
        //         // 先移除现有的绘制交互
        //         this.map.removeInteraction(this.draw)

        //         let drawType;
        //         if (this.select1 == 'line') {
        //             drawType = 'LineString'
        //         } else if (this.select1 == 'circle') {
        //             drawType = 'Circle'
        //         } else if (this.select1 == 'polygon') {
        //             drawType = 'Polygon'
        //         } else {
        //             drawType = 'LineString'
        //         }

        //         // 创建新的绘制交互
        //         this.draw = new Draw({
        //             type: drawType,
        //             source: this.drawLayer.getSource(),
        //             freehand: (this.select1 === 'free'),
        //             style: new Style({
        //                 stroke: new Stroke({
        //                     color: 'red',
        //                     width: 2
        //                 }),
        //                 fill: new Fill({
        //                     color: 'rgba(255,0,0,0.3)'
        //                 })
        //             })
        //         })

        //         // 监听绘制完成事件
        //         this.draw.on('drawend', (event) => {
        //             console.log('绘制完成:', event.feature);
        //             // 绘制完成后，图形会自动添加到 drawLayer 中
        //         });

        //         // 监听绘制开始事件（可选，用于调试）
        //         this.draw.on('drawstart', (event) => {
        //             console.log('开始绘制');
        //         });

        //         this.map.addInteraction(this.draw)

        //         // 确保绘制图层可见
        //         this.drawLayer.setVisible(true)
        //     }
        // }



    }
}
</script>

<style scoped>
.map-page {
    position: relative;
    width: 100%;
    height: 100%;
    min-height: 500px;
}

.header {
    width: 100%;
    height: 80px;
    line-height: 80px;
    background-color: #1677ff;
    display: flex;
    align-items: center;
    gap: 30px;
    color: #fff;
    padding-left: 30px;
    display: fixed;
}

.map-container {
    width: 100%;
    height: calc(100% - 80px);
    background: #f0f0f0;
}



#popup {
    width: 200px;
    height: max-content;
    padding: 10px;
    border-radius: 4px;
    background-color: pink;
    display: none;
    /* 初始隐藏 */
}

/* 当有内容时显示 */
#popup:not(:empty) {
    display: block;
}
</style>